package com.ckzp.jfinal.system.controller;

import cn.dsna.util.images.ValidateCode;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.GifCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.ckzp.core.ConfigUtil;
import com.ckzp.core.Results;
import com.ckzp.core.id.UUIDHex;
import com.ckzp.core.json.Jmode;
import com.ckzp.core.json.JsonResult;
import com.ckzp.core.lc.Aes;
import com.ckzp.core.lc.Md5;
import com.ckzp.core.lc.Pwd;
import com.ckzp.core.model.Datas;
import com.ckzp.core.util.ClientUtil;
import com.ckzp.core.util.JwtUtil;
import com.ckzp.jfinal.base.BaseController;
import com.ckzp.jfinal.form.FormData;
import com.ckzp.jfinal.interceptor.Admins;
import com.ckzp.jfinal.interceptor.Roles;
import com.ckzp.jfinal.system.WebSite;
import com.ckzp.jfinal.system.cache.SysConfigCache;
import com.ckzp.jfinal.system.model.SysUser;
import com.ckzp.jfinal.system.util.LoginUtil;
import com.ckzp.jfinal.system.util.SysOnlineUtil;
import com.ckzp.jfinal.weixin.model.WxMember;
import com.ckzp.weixin.WxTool;
import com.jfinal.aop.Clear;


/**
 * 本类为系统登陆类，密码修改类
 * Created by 51594 on 2019/10/21.
 */
public class LoginController extends BaseController {


    @Clear
    public void index() {
        redirect(ConfigUtil.getFullWebAdminLoginPath());
    }

    /**
     * 登陆界面
     */
    @Clear
    public void login() {
        String TestAdmin = ConfigUtil.getProperty("TEST_USER", "");
        String TestPwd = ConfigUtil.getProperty("TEST_PWD", "");
        if (ConfigUtil.isWindows()) {
            setForm(FormData.n().addData("username", TestAdmin).addData("password", TestPwd).addData("vcode", 9999));
        } else {
            setForm(FormData.n().addData("username", TestAdmin).addData("password", TestPwd));
        }
        setAttr("sys_title", SysConfigCache.getConfigValue("sys_title"));
        setAttr("version", SysConfigCache.getConfigValue("version"));
        if (SysConfigCache.getConfigIntValue("wx_login") == 1) {
           // render("login_wx.html");
            render("login.html");
        } else {
            render("login.html");
        }
    }

    /**
     * 修改密码页面
     */
    @Admins(roles = "login", name = "修改密码页面", log = true)
    public void ChangePwd() {
        setForm(FormData.n().addData("oldpwd", "").addData("newpwd", "").addData("newpwd1", ""));
        // setForm(FormData.n());
        render("ChangePwd.html");
    }


    /**
     * 退出系统
     */
    @Clear
    public void logout() {
        String jwt = WebSite.getJwt(getRequest());
        JwtUtil.JwtPool.AddJwt(jwt);
        WebSite.removeJwt(getRequest(), getResponse());
        redirect(ConfigUtil.getFullWebAdminLoginPath());
    }

    /**
     * 验证登陆
     */
    @Clear
    public void ValidateLoginApi() {
        renderJson(LoginUtil.n().ValidateLogin(getRequest(), getResponse()).toJson());
    }

    /**
     * 修改密码Api
     */
    @Admins(roles = "login", name = "修改密码Api", log = true)
    public void ChangePwdApi() {
        Datas data = getDatas();
        renderJson(LoginUtil.n().ChangePwd(data, getEmpIdStr()).toJson());
    }

    /**
     * 输出 验证码
     */
    @Clear
    public void ValidateCode() {
        try {
            ////120高，40宽，4个数字，10干扰线
            ///////////////////////////////////
            //
            // ValidateCode.jar方式
            ValidateCode vc = new ValidateCode(120, 40, 4, 10);
            // ShearCaptcha （扭曲）
//            ShearCaptcha vc = CaptchaUtil.createShearCaptcha(120, 40, 4, 2);
            // CircleCaptcha（圆圈干扰）
            // CircleCaptcha vc = CaptchaUtil.createCircleCaptcha(120, 40, 4, 4);
            // GifCaptcha生成动态验证码 不可指定位数
            // GifCaptcha vc = CaptchaUtil.createGifCaptcha(120, 40);
            /////////////////////////////////////
            getRequest().getSession().setAttribute("VALIDATECODE", vc.getCode());
            if (DEBUG) Console.log("验证码：{}", vc.getCode());
            vc.write(getResponse().getOutputStream());
            renderNull();
        } catch (Exception e) {
            e.printStackTrace();
            renderNull();
        }
    }

    /**
     * 输出登陆二维码
     */
    @Clear
    public void getWxQrLoginApi() {
        String qr_uuid = UUIDHex.getUUIDHex();
        Results result = WxTool.getWxQrCodeUrl("{type:'web_login',qr_uuid:'" + qr_uuid + "'}");
        result.setKeystring(qr_uuid);
        renderJson(result);
    }

    /**
     * 输出登陆二维码
     */
    @Clear
    public void getWxQrLoginStatusApi() {
        JsonResult jr = JsonResult.n();
        String qr_uuid = getParaStr("qr_uuid", "");
        if (qr_uuid.length() > 20) {
            WxMember member = WxMember.dao.findFirst("select * from wx_member where qr_uuid=? ", qr_uuid);
            if (member != null) {
                int emp_id = member.mod.getInt("emp_id", 0);
                String ip = ClientUtil.getIp(getRequest());
                String os = ClientUtil.getClientOS(getRequest());
                String browser = ClientUtil.getClientBrowser(getRequest());
                jr = LoginUtil.getInstance().validateUserPwdJwt(emp_id, ip);
                if (jr.getCode() == 0) {
                    String jwt = jr.getExtra();
                    WebSite.setJwt(getResponse(), jwt);
                    getRequest().getSession().setAttribute("VALIDATECODE", null);
                    ////////////////////写登陆日志/////////////////
                    String sessid = JwtUtil.getJwtInfo(jwt).getId();
                    int empid = JwtUtil.getJwtInfo(jwt).getUserid();
                    String loginid = JwtUtil.getJwtInfo(jwt).getUsername();
                    /////////////////////写在线用户////////////////////////
                    SysOnlineUtil.n().saveLogin(sessid, empid, ip, os, browser);//
                }
                renderJson(jr);
                return;
            }
        }
        renderJson(JsonResult.n(99, ""));
    }

    /**
     * 输出 随机密码
     */
    @Clear
    public void getRandomPwdApi() {
        renderJson(Jmode.n().set("pwd", Pwd.getRandomPwd()));
    }
}
